<?php
/**
 * Created by PhpStorm.
 * User: 图图
 * Date: 2021-6-8
 * Time: 16:29
 */

namespace app\web\controller;

use app\common\model\ViperActivityProject;
use think\Db;
use think\db\Where;
use app\common\model\ViperType as Viper_type_Model;
use think\Exception;
use app\common\model\RechargeTemplate;
use app\common\model\NumberCardTemplate;
use app\common\model\NumberCardItem;
use app\common\model\MonthCardTemplate;
use app\common\model\MonthCardItem;
use app\common\model\ViperActivityGoods;
use think\Validate;

/**
 * 会员卡类型控制器
 * @package app\index\controller
 */
class ViperType extends Auth
{
    public $noNeedLogin = '';
    /**
     * 基础数据--设置会员类型---添加会员类型
     * name  expire_month  is_across_store_recharge  is_across_store_give
     * is_discount rule  amount integral_1  integral_2
     * recharge  [{ name:'',amount:'',give_amount:'',rate:'',integral:'',type:'',moth:''}]
     * number    [{'name':'','amount':'',rate:'',item:[{id:'',number:'',expire:'',type:'goods'}]}]
     * month    [{name:'',amount:'',rate:'',hz:'',expire:'',type:'',item:[{id:'',type:''}]}]
     * goods
     * [{id:'',type:'',value:'',start:'',end:'',viper_price:'',range_vip_price:'',rule:''}]
     * projects
     * [{id:'',type:'',value:'',start:'',end:'',viper_price:'',add_block_price:'',range_vip_price:'',range_add_block_price:'',rule:''}]
     *
     * viper_price:会员价,add_block_price,加钟价,range_viper_price,时段会员价,range_add_block_price,时段加钟价
     *
     *[{'name':'','amount':'',rate:'',item:[{data:[{'id':'',type:'goods'}],number:'',expire:''}]}]
     *
     * [{name:'',amount:'',rate:'',hz:'',expire:'',type:'',item:[[{data:[{'id':'',type:'goods'}]]}]
     */
    public function add()
    {
        if ($this->request->isPost())
        {
            $data = $this->request->post();

            $validate = new \app\api\validate\ViperType();

            if (!$validate->check($data))
            {
                $this->result($validate->getError(),'',204);
            }
            if(empty($data['integral_2'])){
                $data['integral_2'] = '';
            }
            if(empty($data['integral_1'])){
                $data['integral_1'] = '';
            }
            if(empty($data['use_number_warning'])){
                $data['use_number_warning']= '';
            }
            if(empty($data['use_number_warning'])){
                $data['use_number_warning']= '';
            }
            if(empty($data['birthday_how_long'])){
                $data['birthday_how_long']= 0;
            }
            if(empty($data['silence'])){
                $data['silence']= 0;
            }
            if(empty($data['rule'])){
                $data['rule']= null;
            }
            if(empty($data['amount'])){
                $data['amount']= null;
            }
            $arr = [
                'name'=>$data['name'],
                'expire_month'=>$data['expire_month'],
                'silence'=>$data['silence'],
                'rule'=>$data['rule'],
                'amount'=>$data['amount'],
                'integral_1'=>$data['integral_1'],
                'integral_2'=>$data['integral_2'],
                'use_number_warning'=>$data['use_number_warning'],
                'is_across_store_recharge'=>$data['is_across_store_recharge'],
                'birthday_how_long'=>$data['birthday_how_long'],
                'is_across_store_give'=>$data['is_across_store_give'],
                'is_discount'=>$data['is_discount'],
            ];
            Db::startTrans();

            try {

                $arr['store_id'] = $this->userInfo['store_id'];

                $type = Viper_type_Model::create($arr);

                if (key_exists('recharge',$data)&& !empty($data['recharge'])&&strlen($data['recharge'])>0)
                {
                    $recharge_template = json_decode($data['recharge'],true);
                    RechargeTemplate::createByTemplates($recharge_template,$this->userInfo['store_id'],$type['id'],$this->userInfo['id']);
                }


                if (key_exists('number',$data)&& !empty($data['number'])&&strlen($data['number'])>0)
                {
                    $number_template = json_decode($data['number'],true);
                    NumberCardTemplate::createByTemplate($number_template,$this->userInfo['store_id'],$type['id']);
                }

                if (key_exists('month',$data)&&!empty($data['month'])&&strlen($data['month'])>0)
                {
                    $month_template = json_decode($data['month'],true);

                    MonthCardTemplate::createByTemplate($month_template,$this->userInfo['store_id'],$type['id']);
                }

                if (key_exists('goods',$data)&&!empty($data['goods'])&&strlen($data['goods'])>0)
                {

                    $goods = json_decode($data['goods'],true);

                    ViperActivityGoods::createByTemplate($goods,$this->userInfo['store_id'],$type['id']);
                }

                if (key_exists('projects',$data)&&!empty($data['projects'])&&strlen($data['projects'])>0)
                {

                    $projects = json_decode($data['projects'],true);

                    ViperActivityProject::createByTemplate($projects,$this->userInfo['store_id'],$type['id']);
                }

                Db::commit();
            }catch (Exception $e)
            {
                Db::rollback();

                halt($e->getMessage());
            }
            $this->result('操作成功','',200);

        }else{
            $this->result('操作错误','',204);
        }


    }

    /**
     * 基础数据--设置会员类型---添加或者编辑会员类型
     * name  expire_month  is_across_store_recharge  is_across_store_give
     * is_discount rule  amount integral_1  integral_2
     * viper_type_id
     * recharge[{name:'',amount:'',rate:'',integral:'',month:'',type:''}]
     * number[{'name':'','amount':'',rate:'',item:[{id:'',number:'',expire:'',type:'goods'}]}]
     * month [{name:'',amount:'',rate:'',hz:'',expire:'',type:'',item:[{id:'',type:''}]}]
     * goods
     * [{id:'',type:'',value:'',start:'',end:'',viper_price:'',range_vip_price:''}]
     * projects
     * [{id:'',type:'',value:'',start:'',end:'',viper_price:'',add_block_price:'',range_vip_price:'',range_add_block_price:''}]
     */
    public function edit()
    {
       if ($this->request->isPost())
       {
           $data = $this->request->post();

           $validate = new \app\api\validate\ViperType();

           if (!$validate->check($data))
           {
               $this->result($validate->getError(),'',204);
           }
           if(empty($data['integral_2'])){
               $data['integral_2'] = '';
           }
           if(empty($data['integral_1'])){
               $data['integral_1'] = '';
           }
           if(empty($data['use_number_warning'])){
               $data['use_number_warning']= '';
           }
           if(empty($data['use_number_warning'])){
               $data['use_number_warning']= '';
           }
           if(empty($data['birthday_how_long'])){
               $data['birthday_how_long']= 0;
           }
           if(empty($data['silence'])){
               $data['silence']= 0;
           }
           if(empty($data['rule'])){
               $data['rule']= null;
           }
           if(empty($data['amount'])){
               $data['amount']= null;
           }
           $arr = [
               'name'=>$data['name'],
               'expire_month'=>$data['expire_month'],
               'silence'=>$data['silence'],
               'rule'=>$data['rule'],
               'amount'=>$data['amount'],
               'integral_1'=>$data['rule'],
               'integral_2'=>$data['integral_2'],
               'use_number_warning'=>$data['use_number_warning'],
               'is_across_store_recharge'=>$data['is_across_store_recharge'],
               'birthday_how_long'=>$data['birthday_how_long'],
               'is_across_store_give'=>$data['is_across_store_give'],
               'is_discount'=>$data['is_discount'],
           ];
           //删除模板
           if(isset($data['del_data']) && $data['del_data'] != ""){
               $del_data = json_decode($data['del_data'],true);
               foreach ($del_data as $key=>$value){
                   if($value['type'] == '1'){
                       $bool = $this->del_recharge_template($value['id']);
                   }else if($value['type'] == '2'){
                       $bool = $this->del_number_template($value['id']);
                   }else if($value['type'] == '3'){
                       $bool =  $this->del_month_template($value['id']);
                   }
                   if($bool == false){
                       $this->result('系统繁忙，请稍后再试','',204);
                   }
               }
           }
           if (!$data['viper_type_id'])
               $this->result('缺少必要参数','',204);
           Db::startTrans();
           try {
               Viper_type_Model::where('id',$data['viper_type_id'])->update($arr);
               if (key_exists('recharge',$data)&&!empty($data['recharge'])&&strlen($data['recharge'])>0)
               {
                   Db::name('qt_viper_recharge_template_return')->where(['viper_type_id'=>$data['viper_type_id']])->delete();

                   $recharge_template = json_decode($data['recharge'],true);

                   RechargeTemplate::updateByTemplates($recharge_template,$this->userInfo['store_id'],$data['viper_type_id'],$this->userInfo['id']);
               }
               if (key_exists('number',$data)&&!empty($data['number'])&&strlen($data['number'])>0)
               {
                   $number_template = json_decode($data['number'],true);
                   $number_template_card = Db::name('qt_viper_number_card_template')->where('viper_type_id',$data['viper_type_id'])->find();
                   //DB::name('qt_viper_number_card_template')->where(['viper_type_id'=>$data['viper_type_id'],'type'=>'1'])->delete();
                   DB::name('qt_viper_number_card_template_collection')->where('number_template_id',$number_template_card['id'])->delete();
                   DB::name('qt_viper_number_card_template_item')->where(['number_card_template_id'=>$number_template_card['id'],'type'=>'1'])->delete();
                   NumberCardTemplate::updateByTemplate($number_template,$this->userInfo['store_id'],$data['viper_type_id']);
               }
               if (key_exists('month',$data) && !empty($data['month'])&&strlen($data['month'])>0) {
                   $month_template = json_decode($data['month'],true);
                   //MonthCardTemplate::where(['store_id'=>$this->userInfo['store_id'],'viper_type_id'=>$data['viper_type_id'],'template_type'=>'1'])->delete();
                   $month_template_card = Db::name('qt_viper_month_card_template')->where('viper_type_id',$data['viper_type_id'])->find();
                   MonthCardItem::where(['month_template_id'=>$month_template_card['id'],'template_type'=>'1'])->delete();
                   MonthCardTemplate::updateByTemplate($month_template,$this->userInfo['store_id'],$data['viper_type_id']);
               }

               if (key_exists('goods',$data)&&!empty($data['goods'])&&strlen($data['goods'])>0)
               {

                   $goods = json_decode($data['goods'],true);

                   DB::name('qt_viper_activity_goods')->where(['store_id'=>$this->userInfo['store_id'],'viper_type_id'=>$data['viper_type_id']])->delete();

                   ViperActivityGoods::createByTemplate($goods,$this->userInfo['store_id'],$data['viper_type_id']);
               }

               if (key_exists('projects',$data)&&!empty($data['projects'])&&strlen($data['projects'])>0)
               {

                   $projects = json_decode($data['projects'],true);

                   DB::name('qt_viper_activity_project')->where(['store_id'=>$this->userInfo['store_id'],'viper_type_id'=>$data['viper_type_id']])->delete();

                   ViperActivityProject::createByTemplate($projects,$this->userInfo['store_id'],$data['viper_type_id']);
               }

               Db::commit();

           }catch (Exception $e){
               Db::rollback();
               $this->result('请求错误'.$e->getMessage().' 文件：'.$e->getFile().' 行数：'.$e->getLine(),'',204);
           }

           $this->result('操作成功','',200);

       }else{
           $this->result('请求错误','',204);
       }
    }

    /**
     * 基本数据--会员类型管理--会员类型详情
     * viper_type_id
     *
     */
    public function detail()
    {
        if ($this->request->isPost())
        {
            $viper_type_id = $this->request->post('viper_type_id');

            if (empty($viper_type_id))
                    $this->result('缺少必要参数','',204);

            $info = Viper_type_Model::where(['store_id'=>$this->userInfo['store_id'],'id'=>$viper_type_id])
                ->field('id,name,expire_month,silence,rule,amount,integral_1,integral_2,is_across_store_recharge,is_across_store_give,is_discount,use_number_warning,birthday_how_long')
                ->find();
            $info['recharge'] = RechargeTemplate::getTemplateOfStore($this->userInfo['store_id'],$viper_type_id);
            $info['number'] = NumberCardTemplate::getTemplateOfStore($this->userInfo['store_id'],$viper_type_id);
            $info['month'] = MonthCardTemplate::getTemplateOfStore($this->userInfo['store_id'],$viper_type_id);
            $info['goods'] =ViperActivityGoods::getActivityGoodsOfStore($this->userInfo['store_id'],$viper_type_id);
            $info['projects'] = ViperActivityProject::getActivityProjectOfStore($this->userInfo['store_id'],$viper_type_id);

            $this->result('获取成功',$info,200);

        }else{
            $this->result('请求错误','',204);
        }
    }

    /**
     * 基本数据--会员类型管理--会员类型列表
     */
    public function lists()
    {
        if ($this->request->isPost())
        {
            $list = Db::name('qt_viper_type')->where(['store_id'=>$this->userInfo['store_id']])->field('id,name,amount_percentage,give_amount_percentage')->select();
            $this->result('获取成功',$list,200);
        }else{
            $this->result('请求错误','',204);
        }
    }

    /**
     * 基本数据--会员类型--删除会员类型
     */
    public function remove()
    {
        if ($this->request->isPost())
        {
            $data = $this->request->post();

            if (empty($data['viper_type_id']))
                $this->result('缺少必要参数','',204);
            $find = Db::name('qt_viper_card')->where('viper_type_id',$data['viper_type_id'])->find();
            if(!empty($find)){
                $this->result('该会员卡下面有会员，暂时不支持删除','',204);
            }
            $result = Viper_type_Model::destroy($data['viper_type_id']);

            $result?$this->result('删除成功','',200):$this->result('删除失败','',204);
        }else{
            $this->result('请求错误','',204);
        }
    }



    /**
     * 设置支付比例
     */
    public function percentage()
    {
        if ($this->request->isPost())
        {
            $getData = $this->request->post();
            $rule = [
                'amount_percentage'  =>  'require',
                'give_amount_percentage' =>  'require',
                'viper_type_id' =>  'require',
            ];
            $message  =   [
                'amount_percentage'  =>  '本金比例不能为空',
                'give_amount_percentage' =>  '赠送比例不能为空',
                'viper_type_id' =>  '会员卡ID不能为空',
            ];
            // 验证
            $validate = new Validate($rule,$message);
            if(!$validate->check($getData)){
                $this->result($validate->getError(),'',204);
            }

            if(($getData['amount_percentage'] + $getData['give_amount_percentage']) != 100){
                $this->result('支付比例相加必须等于100','',204);
            }
            $update = Db::name('qt_viper_type')->where(['id'=>$getData['viper_type_id']])->update([
                'amount_percentage'=>$getData['amount_percentage'],
                'give_amount_percentage'=>$getData['give_amount_percentage']
            ]);
            if($update !== false){
                $this->result('设置成功','',200);
            }
            $this->result('设置失败','',204);
        }else{
            $this->result('请求错误','',204);
        }
    }


    /**
     * 删除充值模板
     * @parm $rechargeTemplateId [充值模板ID]
     * @return bool
     */
    public function del_recharge_template($rechargeTemplateId){
        try{
            Db::startTrans();
            $viperType = Db::name('qt_viper_recharge_template')->where(['id'=>$rechargeTemplateId])->value('viper_type_id');
            Db::name('qt_viper_recharge_template')->where(['id'=>$rechargeTemplateId])->delete();
            Db::name('qt_viper_recharge_template_return')->where(['template_id'=>$rechargeTemplateId,'viper_type_id'=>$viperType])->delete();
            Db::commit();
        }catch (Exception $exception){
            Db::rollback();
            return false;

        }
        return true;
    }


    /**
     * 删除次卡模板
     * @parm $numberTemplateId [次卡模板ID]
     * @return bool
     */
    public function del_number_template($numberTemplateId){

        try{
            Db::startTrans();
            //删除次卡
            Db::name('qt_viper_number_card_template')->where(['id'=>$numberTemplateId])->delete();
            //删除次卡合集
            Db::name('qt_viper_number_card_template_collection')->where(['number_template_id'=>$numberTemplateId])->delete();
            //删除次卡包含的项目
            Db::name('qt_viper_number_card_template_item')->where(['number_card_template_id'=>$numberTemplateId])->delete();
            Db::commit();
        }catch (Exception $exception){
            Db::rollback();
            return false;
        }
        return true;

    }
    /**
     * 删除月卡模板
     * @parm $monthTemplateId [月卡模板ID]
     * @return bool
     */
    public function del_month_template($monthTemplateId){
        try{
            Db::startTrans();
            //删除月卡模板
            Db::name('qt_viper_month_card_template')->where(['id'=>$monthTemplateId])->delete();
            //删除模板明细
            Db::name('qt_viper_month_card_template_item')->where(['month_template_id'=>$monthTemplateId])->delete();
            Db::commit();
        }catch (Exception $exception){
            Db::rollback();
            return false;
        }
        return true;
    }



}
